// 通知消息模块

import { Module } from "vuex"
export enum TypesMsg {
  /** 消息通知 */
  "sendMsg" = "sendMsg",
  /** 审核通知 */
  "auditMsg" = "auditMsg",
  /** 审核通知 */
  "memberCartOpen" = "memberCartOpen",
  /** 订单退款 */
  "orderRefund" = "orderRefund",
  /** 订单退款 */
  "orderRefundNotify" = "orderRefundNotify",
}

export interface IMessage {
  id: string;
  mark: string;
  miniTemplateId: string;
  miniOpen: number;
  miniMsg: string;
}

export interface State {
  templates: IMessage[];
  type: TypesMsg;
  templateMap: Map;
  templateSatusMap: Map;
}

export interface Map {
  [porp: string]: number | string
}

const module: Module<any, any> = {
  namespaced: true,
  state: {
    /** 模板列表 */
    templates: [] as IMessage[],

    type: {
      /** 消息通知 */
      sendMsg : "sendMsg",
      /** 审核通知 */
      auditMsg : "auditMsg",
      /** 审核通知 */
      memberCartOpen : "memberCartOpen",
      /** 订单退款 */
      orderRefund : "orderRefund",
      /** 订单退款 */
      orderRefundNotify : "orderRefundNotify",
    },
  },
  getters: {
    /** 模板列表ID */
    templateMap: (state: State) => {
      const map: Map = {};
      state.templates.forEach(({ mark, miniTemplateId }) => {
        map[mark] = miniTemplateId;
      });
      return map;
    },

    /** 模板可用状态 */
    templateSatusMap: (state: State) => {
      const map: Map = {};
      state.templates.forEach(({ mark, miniOpen }) => {
        map[mark] = miniOpen;
      });
      return map;
    },


  },
  mutations: {
    /** 获取模板列表 */
    getTemplates(state: State, templates: IMessage[]) {
      state.templates = templates;
    },

    
  },
  actions: {
    /**
     * 订阅消息
     * @param tmplIds 模板id数组
     * 只会返回resolve true 表示成功 false 表示失败
     */
     subscribe(context, ids: Array<string>): Promise<boolean> {
      // return Promise.resolve(false);
      if (!context.state.templates || !context.state.templates.length) {
        return Promise.resolve(false);
      }
      
      const tmplIds = ids
        .filter(item => context.getters.templateSatusMap[item])
        .map(key => context.getters.templateMap[key]);

      if (!tmplIds.length) return Promise.resolve(false);

      return new Promise(resolve => {
        uni.requestSubscribeMessage({
          tmplIds,
          success: () => resolve(true),
          fail: err => {
            console.log('message.ts line 101 err',err)
            resolve(false);
          },
          complete: () => resolve(false),
        });
      });
    },

    /**
     * 获取templatid
     * @param mark
     */
    getTemplateId(context, mark: string) {
      return context.getters.templateMap[mark];
    },
  }
}

export default module;
